{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# reallocate_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/reallocate_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/reallocate_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "Reallocate production to smooth it over years.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "def main():\n",
    "    # Data\n",
    "    data_0 = [\n",
    "        [107, 107, 107, 0, 0],  # pr1\n",
    "        [0, 47, 47, 47, 0],  # pr2\n",
    "        [10, 10, 10, 0, 0],  # pr3\n",
    "        [0, 55, 55, 55, 55],  # pr4\n",
    "    ]\n",
    "\n",
    "    data_1 = [\n",
    "        [119444030, 0, 0, 0],\n",
    "        [34585586, 38358559, 31860661, 0],\n",
    "        [19654655, 21798799, 18106106, 0],\n",
    "        [298836792, 0, 0, 0],\n",
    "        [3713428, 4118530, 4107277, 3072018],\n",
    "        [6477273, 7183884, 5358471, 0],\n",
    "        [1485371, 1647412, 1642911, 1228807],\n",
    "    ]\n",
    "\n",
    "    data_2 = [\n",
    "        [1194440, 0, 0, 0],\n",
    "        [345855, 383585, 318606, 0],\n",
    "        [196546, 217987, 181061, 0],\n",
    "        [2988367, 0, 0, 0],\n",
    "        [37134, 41185, 41072, 30720],\n",
    "        [64772, 71838, 53584, 0],\n",
    "        [14853, 16474, 16429, 12288],\n",
    "    ]\n",
    "\n",
    "    pr = data_0\n",
    "\n",
    "    num_pr = len(pr)\n",
    "    num_years = len(pr[1])\n",
    "    total = sum(pr[p][y] for p in range(num_pr) for y in range(num_years))\n",
    "    avg = total // num_years\n",
    "\n",
    "    # Model\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # Variables\n",
    "    delta = model.NewIntVar(0, total, \"delta\")\n",
    "\n",
    "    contributions_per_years = collections.defaultdict(list)\n",
    "    contributions_per_prs = collections.defaultdict(list)\n",
    "    all_contribs = {}\n",
    "\n",
    "    for p, inner_l in enumerate(pr):\n",
    "        for y, item in enumerate(inner_l):\n",
    "            if item != 0:\n",
    "                contrib = model.NewIntVar(0, total, \"r%d c%d\" % (p, y))\n",
    "                contributions_per_years[y].append(contrib)\n",
    "                contributions_per_prs[p].append(contrib)\n",
    "                all_contribs[p, y] = contrib\n",
    "\n",
    "    year_var = [model.NewIntVar(0, total, \"y[%i]\" % i) for i in range(num_years)]\n",
    "\n",
    "    # Constraints\n",
    "\n",
    "    # Maintain year_var.\n",
    "    for y in range(num_years):\n",
    "        model.Add(year_var[y] == sum(contributions_per_years[y]))\n",
    "\n",
    "    # Fixed contributions per pr.\n",
    "    for p in range(num_pr):\n",
    "        model.Add(sum(pr[p]) == sum(contributions_per_prs[p]))\n",
    "\n",
    "    # Link delta with variables.\n",
    "    for y in range(num_years):\n",
    "        model.Add(year_var[y] >= avg - delta)\n",
    "\n",
    "    for y in range(num_years):\n",
    "        model.Add(year_var[y] <= avg + delta)\n",
    "\n",
    "    # Solve and output\n",
    "    model.Minimize(delta)\n",
    "\n",
    "    # Solve model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    status = solver.Solve(model)\n",
    "\n",
    "    # Output solution.\n",
    "    if status == cp_model.OPTIMAL:\n",
    "        print(\"Data\")\n",
    "        print(\"  - total = \", total)\n",
    "        print(\"  - year_average = \", avg)\n",
    "        print(\"  - number of projects = \", num_pr)\n",
    "        print(\"  - number of years = \", num_years)\n",
    "\n",
    "        print(\"  - input production\")\n",
    "        for p in range(num_pr):\n",
    "            for y in range(num_years):\n",
    "                if pr[p][y] == 0:\n",
    "                    print(\"        \", end=\"\")\n",
    "                else:\n",
    "                    print(\"%10i\" % pr[p][y], end=\"\")\n",
    "            print()\n",
    "\n",
    "        print(\"Solution\")\n",
    "        for p in range(num_pr):\n",
    "            for y in range(num_years):\n",
    "                if pr[p][y] == 0:\n",
    "                    print(\"        \", end=\"\")\n",
    "                else:\n",
    "                    print(\"%10i\" % solver.Value(all_contribs[p, y]), end=\"\")\n",
    "            print()\n",
    "\n",
    "        for y in range(num_years):\n",
    "            print(\"%10i\" % solver.Value(year_var[y]), end=\"\")\n",
    "        print()\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
